package com.swm.julie.rest.crud.twitt.search;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.queryParser.ParseException;

import com.swm.julie.rest.crud.twitt.TwittDocFormat;

@SuppressWarnings("serial")
public class SearchTwittServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//		req.setCharacterEncoding("UTF-8");
		//		
		//		String query = req.getParameter("query");
		//		SearchTwitt searcher = new SearchTwitt();
		//		
		//		searcher.setIndexDir("D:\\tempNewTwitt");
		//		try 
		//		{
		//			ArrayList<TwittDocFormat> result = searcher.search(query);
		//			
		//			if(result == null || result.size() == 0)
		//			{
		//				req.setAttribute("result", null);
		//			}else
		//			{
		//				req.setAttribute("result", result);
		//			}
		//			
		//		} catch (ParseException e) {
		//			// TODO Auto-generated catch block
		//			///If occurs in parseException, then the result is the same with no result
		//			e.printStackTrace();
		//			req.setAttribute("result", null);
		//		}
		//		
		//		//Dispatch to the view page
		//		System.out.println("SearchTwittServlet.doGet() : Dispatch to searchResult.jsp");
		//		RequestDispatcher view = req.getRequestDispatcher("searchResult.jsp");
		//		view.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("UTF-8");

		String query = req.getParameter("query");
		SearchTwitt searcher = new SearchTwitt();

		searcher.setIndexDir(System.getProperty("user.dir") + "/tempNewTwitt");
		try 
		{
			ArrayList<TwittDocFormat> result = searcher.search(query);

			if(result == null || result.size() == 0)
			{
				req.setAttribute("result", null);
			}else
			{
				req.setAttribute("result", result);
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			///If occurs in parseException, then the result is the same with no result
			e.printStackTrace();
			req.setAttribute("result", null);
		}

		//Dispatch to the view page
		System.out.println("SearchTwittServlet.doGet() : Dispatch to searchResult.jsp");
		RequestDispatcher view = req.getRequestDispatcher("searchResult.jsp");
		view.forward(req, resp);
	}
}
